
from views.db import db
# 封装rbac

class RBAC:

    def __init__(self):


        pass

    # 添加权限
    def set_role_resource(self,roleid,reslist):
        for i in reslist:
            sql = "insert into role values(%d,%d)"%(int(roleid),int(i))
            db.update(sql)

    # 修改权限
    def update_role_resource(self,roleid,reslist):
        sql = "delete from role where roleid=%d "%(int(roleid))
        db.update(sql)
        self.set_role_resource(roleid,reslist)


    # 删除单个权限
    def delete_role_resource(self,roleid,resourceid):
        sql = "delete from role where roleid=%d and resourceid=%d"%(int(roleid),int(resourceid))
        db.update(sql)


    # 获取页面资源列表   1为前端页面资源
    def get_pagedef_reslist(self,uid):
        sql = "select roleid from user_role where uid=%d" % int(uid)
        res = db.get_all(sql)
        for i in res:
            sql1 = "select r.url as url from role as ro inner join resource as r on ro.resourceid=r.id where ro.roleid=%d and r.type=1" % (int(i['roleid']))
            res1 = db.get_all(sql1)
            lst = []
            for j in res1:
                lst.append(j['url'])
            
            return lst

    # 查询用户资源
    def get_userresource(self,uid,type):

      
        sql = " select r.id,r.name,r.url,pr.id as pid,pr.name as pname from user_role as ur left join role_resource as rr on ur.roleid = rr.roleid left join resource as r on rr.resourceid=r.id left join resource as pr on pr.id = r.pid where ur.uid = %d and r.type=%d " (int(uid),int(type))

        res = db.get_all(sql)

        return res


rbac = RBAC()
